package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse resp=(HttpServletResponse) response;

        //获取url
        String url = req.getRequestURL().toString();
        log.info("请求的url,{}", url);


        //是登录操作
        if(url.contains("login")){
            log.info("登录操作");
            chain.doFilter(request,response);  //提前放行
            return;
        }

        //获取请求头的令牌 token
        String jwt = req.getHeader("token");

        //令牌不存在 返回错误信息
        if(!StringUtils.hasLength(jwt)){
            log.info("解析令牌失败，返回未登录的信息");
            Result error = Result.error("NOT_LOGIN");
            //手动转换 对象---->json
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);  //返回错误信息
            return;
        }


        //解析token 如果解析失败 返回错误结果
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) { //解析失败
            e.printStackTrace();
            log.info("解析令牌失败，返回未登录的信息");
            Result error = Result.error("NOT_LOGIN");
            //手动转换 对象---->json
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);   //返回错误信息
            return;
        }

        //放行
        log.info("令牌合法");
        chain.doFilter(request,response);

    }
}
